// components/trolley/trolley.js
const computedBehavior = require('miniprogram-computed').behavior
Component({
  behaviors: [computedBehavior],
  /**
   * 组件的属性列表
   */

  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    // 商品列表
    list: []
  },
  pageLifetimes: {
    show() {
      let cart = wx.getStorageSync('cart') || []
      this.setData({
        list: cart
      })
    }

  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 获取复选框的状态
    singleCheck(e) {
      let index = e.currentTarget.dataset.index
      this.data.list[index].checked = !this.data.list[index].checked
      this.setData({
        list: this.data.list
      })
    },
    // 减
    minus(e) {
      let index = e.currentTarget.dataset.index
      if (this.data.list[index].count > 1) {
        this.data.list[index].count--
        this.setData({
          list: this.data.list
        })
        wx.setStorageSync('cart', this.data.list)
      }

    },
    // 加
    add(e) {
      let index = e.currentTarget.dataset.index
      this.data.list[index].count++
      this.setData({
        list: this.data.list
      })
      wx.setStorageSync('cart', this.data.list)
    },
    // 点击全选实现复选
    twoAll() {
      let falg = this.data.list.every(item => item.checked)
      this.data.list.forEach(item => {
        item.checked = !falg
      })
      this.setData({
        list: this.data.list
      })
    },
    // 删除
    del(e) {
      console.log(e);
      let index = e.currentTarget.dataset.index
      this.data.list.splice(index, 1)
      this.setData({
        list: this.data.list
      })
      wx.setStorageSync('cart', this.data.list)
    }
  },
  computed: {
    totalPrice(data) {
      return data.list.reduce((total, item) => {
        if (item.checked) {
          return total += item.price * item.count
        } else {
          return total
        }
      }, 0)
    },
    // 点击复选实现全选
    checkAll(data) {
      if(data.list.length){ 
        return data.list.every(item => {
          return item.checked
        })
      }else{ 
        return false
      }
 

    }
  }
})